<template>
  <div>
    <header>
      <a-page-header style="border: 1px solid rgb(235, 237, 240)" title="数据统计"/>
    </header>
    <section style="margin-top: 8px;">
      <a-row :gutter="16">
        <a-col :span="12">
            <a-card title="帖子内容发布统计" hoverable>
              <div ref="pieCharts" id="pieCharts" style="height: 400px;"></div>
            </a-card>
        </a-col>
        <a-col :span="12">
          <a-card title="近七天用户发帖数量" hoverable>
              <div ref="discountCharts" id="discountCharts" style="height: 400px;"></div>
            </a-card>
        </a-col>
      </a-row>
    </section>
  </div>
</template>

<script setup>
import { ref, onMounted,onBeforeUnmount } from 'vue';
import { Chart } from '@antv/g2';
import { getStatistics } from '@/apis/admin';

const pieCharts = ref(null);
let pieChart = null;
const discountCharts = ref(null);
let discountChart = null;

const renderPieCharts = (data=[]) => {
  pieChart = new Chart({
    container: pieCharts.value,
    autoFit: true,
    height: 400,
  });
  pieChart.coordinate({ type: 'theta', outerRadius: 0.8 });
  pieChart
  .interval()
  .data(data?.filter(item => item.postCount > 0))
  .transform({ type: 'stackY' })
  .encode('y', 'postCount')
  .encode('color', 'plateName')
  .legend('color', { position: 'top', layout: { justifyContent: 'center' } })
  .label({
    position: 'outside',
    text: (data) => `${data.plateName}`,
  })
  .tooltip((data) => ({
    name: data.plateName,
    value: `${data.postCount}`,
  }))

  pieChart.render();

};
const renderDiscountCharts = (data=[]) => {
  discountChart = new Chart({
  container: discountCharts.value,
  autoFit: true,
  height: 400,
});

discountChart
  .data(data)
  .encode('x', 'postDate')
  .encode('y', 'postCount')
  .scale('x', {
    range: [0, 1],
  })
  .scale('y', {
    domainMin: 0,
    nice: true,
  });
  discountChart.line().label({
  text: 'postCount',
  style: {
    dx: -10,
    dy: -12,
  },
});
discountChart.axis('x', {
  title: '日期'
}).axis('y',{title: '发帖数量'});

discountChart.point().style('fill', 'white')

discountChart.render();
};


const init = async () => {


  try {
    const { data = {} } = await getStatistics();
    renderDiscountCharts(data?.weekPostCount);
    renderPieCharts(data?.plateDistribution);
  } catch (error) {
    console.log(error, 'get-statistics-error');

  }
};

onMounted(() => {
  init();
});

onBeforeUnmount(() => {
  if (discountChart) {
    discountChart.destroy();
  }
});
</script>

<style lang="less" scoped></style>
